/* eslint-disable @typescript-eslint/no-var-requires */
import { Injectable } from '@nestjs/common';
import axios from 'axios';
import { PayDto } from '../dto/pay.dto';
import { OrderRefundDto } from '../dto/orderRefund.dto';
import { OrderService } from '@/modules/shop/services';
import alipaySdk from '@/modules/core/util/alipayUtil';
import { ORDER_STATUS } from '@/modules/shop/contance';
import { User } from '@/modules/User/types';
const AlipayFormData = require('alipay-sdk/lib/form');
@Injectable()
export class PayService {
  constructor(private orderService: OrderService) {}
  async pay(body: PayDto) {
    try {
      const orderId = body.orderId;
      const formData = new AlipayFormData();
      formData.setMethod('get');
      formData.addField('bizContent', {
        outTradeNo: orderId, // 商户订单号,64个字符以内、可包含字母、数字、下划线,且不能重复
        productCode: 'FAST_INSTANT_TRADE_PAY', // 销售产品码，与支付宝签约的产品码名称,仅支持FAST_INSTANT_TRADE_PAY
        totalAmount: String(body.totalPrice), // 订单总金额，单位为元，精确到小数点后两位
        subject: '商品', // 订单标题
        body: '商品详情', // 订单描述
      });
      formData.addField('returnUrl', body.returnUrl);
      formData.addField(
        'notify_url',
        'https://e8cd-122-96-31-221.ngrok.io/pay/notify',
      );
      const result = await alipaySdk.exec(
        // result 为可以跳转到支付链接的 url
        'alipay.trade.page.pay', // 统一收单下单并支付页面接口
        {}, // api 请求的参数（包含“公共请求参数”和“业务参数”）
        { formData: formData },
      );

      return {
        message: '发起支付成功',
        statusCode: 200,
        data: result,
      };
    } catch (error) {
      return {
        message: '订单支付失败',
        statusCode: 500,
        data: error.message,
      };
    }
  }

  async orderQuery(user: User, orderId: string) {
    try {
      const formData = new AlipayFormData();
      formData.setMethod('get');
      formData.addField('bizContent', {
        outTradeNo: orderId, // 商户订单号,64个字符以内、可包含字母、数字、下划线,且不能重复
      });
      const result = await alipaySdk.exec(
        // result 为可以跳转到支付链接的 url
        'alipay.trade.query', // 统一收单下单并支付页面接口
        {}, // api 请求的参数（包含“公共请求参数”和“业务参数”）
        { formData: formData },
      );
      const res = await axios.get(result);
      if (res.data.alipay_trade_query_response.code == 10000) {
        const order = await this.orderService.update(user, orderId, {
          status: ORDER_STATUS.wait_send,
        });
        return {
          message: '订单查询成功',
          statusCode: 200,
        };
      } else {
        return {
          message: '订单查询失败',
          statusCode: 500,
          data: res.data,
        };
      }
    } catch (error) {
      return {
        message: '订单查询失败',
        statusCode: 500,
        data: error.message,
      };
    }
  }
  async orderRefund(body: OrderRefundDto) {
    try {
      const orderId = body.orderId;
      const refundAmount = body.totalPrice;
      const outRequestNo = 'fff21332';
      const formData = new AlipayFormData();
      formData.setMethod('get');
      formData.addField('bizContent', {
        outTradeNo: orderId, // 商户订单号,64个字符以内、可包含字母、数字、下划线,且不能重复
        refundAmount: refundAmount, // 退款金额
        outRequestNo: outRequestNo, // 商户订单号,64个字符以内、可包含字母、数字、下划线,且不能重复
      });
      const result = await alipaySdk.exec(
        // result 为可以跳转到支付链接的 url
        'alipay.trade.refund', // 统一收单下单并支付页面接口
        {}, // api 请求的参数（包含“公共请求参数”和“业务参数”）
        { formData: formData },
      );
      return {
        message: '订单退款成功',
        statusCode: 200,
        data: result,
      };
    } catch (error) {
      return {
        message: '订单退款失败',
        statusCode: 500,
        data: error.message,
      };
    }
  }
  async orderRefundQuery(query: any) {
    const orderId = query.orderId;
    const outRequestNo = query.outRequestNo;
    const formData = new AlipayFormData();
    formData.setMethod('get');
    formData.addField('bizContent', {
      outTradeNo: orderId, // 商户订单号,64个字符以内、可包含字母、数字、下划线,且不能重复
      outRequestNo: outRequestNo,
    });
    const result = await alipaySdk.exec(
      // result 为可以跳转到支付链接的 url
      'alipay.trade.fastpay.refund.query', // 统一收单下单并支付页面接口
      {}, // api 请求的参数（包含“公共请求参数”和“业务参数”）
      { formData: formData },
    );
    return {
      message: '订单退款查询成功',
      statusCode: 200,
      result: result,
    };
  }

  async notify(body: any) {
    console.log('123123通知结果', body);
    return 'ok';
  }

  async notify2(body: any) {
    console.log('123123通知结果');
    return 'ok';
  }
}
